package com.wfh.blog.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice//拦截所有的controller注解
public class ControllerExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());//得到logger对象

    @ExceptionHandler(Exception.class) //这个方法是处理异常的方法
    public ModelAndView exceptionHandler(HttpServletRequest request,Exception e) throws Exception {
        logger.error("Request URL : {},Exception : {}",request.getRequestURL(),e); //日志记录错误

        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {//如果有注解状态码，向上抛出异常，交给springboot自己处理
            throw e;
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("url", request.getRequestURL());
        mv.addObject("exception", e);
        mv.setViewName("error/error");
        return mv;
    }
}
